package middleware

import (
	"bytes"
	"compress/gzip"
	"net/http"

	"gitee.com/shoyer/framework/ctx"
	"gitee.com/shoyer/framework/enums/Encode"
)

func getEncode(ctx *ctx.Ctx, w http.ResponseWriter, data []byte) (result []byte, err error) {
	buf := &bytes.Buffer{}

	switch ctx.GetEncode() {
	case Encode.Gzip:
		buf, err = getGzipEncode(w, data)
	default:
		return data, nil
	}

	if err != nil {
		return
	}

	result = buf.Bytes()

	return
}

func getGzipEncode(w http.ResponseWriter, data []byte) (result *bytes.Buffer, err error) {
	buf := &bytes.Buffer{}
	gw := gzip.NewWriter(buf)
	defer gw.Close()
	_, err = gw.Write(data)
	if err != nil {
		return
	}
	gw.Flush()

	w.Header().Set("Content-Encoding", "gzip")

	return buf, nil
}
